package com.wtp.wallpaper.interceptor;

import com.wtp.wallpaper.common.constant.JwtClaimsConstant;
import com.wtp.wallpaper.common.context.BaseContext;
import com.wtp.wallpaper.common.properties.JwtProperties;
import com.wtp.wallpaper.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class JwtAdminTokenInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String requestURI = request.getRequestURI();
        log.info("拦截的路径为:{}",requestURI);

        //log.info("请求头信息:{}",request);

        // 允许OPTIONS请求通过
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            log.info("OPTIONS 请求不需要验证 token");
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = request.getHeader(jwtProperties.getAdminTokenName());

        try{
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            log.info("当前claims:{}", claims);
            String userid = claims.get(JwtClaimsConstant.USER_ID,String.class);
            String phone = claims.get(JwtClaimsConstant.PHONE, String.class);
            String nickname = claims.get(JwtClaimsConstant.NICKNAME, String.class);

            log.info("当前用户:{}",userid);
            log.info("当前用户手机号:{}",phone);
            log.info("当前用户昵称:{}",nickname);

            Map<String,Object> map = new HashMap<>();
            map.put(JwtClaimsConstant.PHONE,phone);
            map.put(JwtClaimsConstant.USER_ID,userid);
            map.put(JwtClaimsConstant.NICKNAME,nickname );

            BaseContext.setCurrentMap(map);
            BaseContext.setCurrentId(userid);

            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }

}
